import firebase from "firebase/app";
import "firebase/auth";
import db from "../firebase/firebaseInit";

export default {
  async getCurrentUser({ commit }, user) {
    const dataBase = await db
      .collection("users")
      .doc(firebase.auth().currentUser.uid);
    const dbResults = await dataBase.get();
    commit("setProfileInfo", dbResults);
    commit("setProfileInitials");
    const token = await user.getIdTokenResult();
    const admin = await token.claims.admin;
    commit("setProfileAdmin", admin);
  },
  async getPost({ state }) {
    const dataBase = await db.collection("blogPosts").orderBy("date", "desc");
    const dbResults = await dataBase.get();
    dbResults.forEach((doc) => {
      if (!state.blogPosts.some((post) => post.blogID === doc.id)) {
        const data = {
          blogID: doc.data().blogID,
          blogHTML: doc.data().blogHTML,
          blogCoverPhoto: doc.data().blogCoverPhoto,
          blogTitle: doc.data().blogTitle,
          blogDate: doc.data().date,
          blogCoverPhotoName: doc.data().blogCoverPhotoName,
        };
        state.blogPosts.push(data);
      }
    });
    state.postLoaded = true;
  },
  async updatePost({ commit, dispatch }, payload) {
    commit("filterBlogPost", payload);
    await dispatch("getPost");
  },
  async deletePost({ commit }, payload) {
    const getPost = await db.collection("blogPosts").doc(payload);
    await getPost.delete();
    commit("filterBlogPost", payload);
  },
  async updateUserSettings({ commit, state }) {
    const dataBase = await db.collection("users").doc(state.profileId);
    await dataBase.update({
      firstName: state.profileFirstName,
      lastName: state.profileLastName,
      username: state.profileUsername,
    });
    commit("setProfileInitials");
  },
};
